<template>
  <div class="favorites-container">
    <a-page-header title="My Favorites" sub-title="Manage your favorite products"/>

    <a-spin :spinning="loading">
      <div v-if="favorites.length === 0" class="empty-state">
        <a-empty description="No favorite products"/>
        <a-button type="primary" @click="goToProducts">Go to products</a-button>
      </div>

      <a-list
        v-else
        :grid="{ gutter: 6, xs: 1, sm: 2, md: 2, lg: 3, xl: 3, xxl: 4 }"
        :data-source="favorites"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-card hoverable @click="viewProductDetail(item)">
              <template #cover>
                <img v-if="item.images && item.images.length > 0" :src="item.images[0]" alt="商品图片" style="height: 400px; object-fit: cover;"/>
                <div v-else class="no-image">No image</div>
              </template>
              <a-card-meta :title="item.name">
                <template #description>
                  <div class="product-price-container">
                    <div class="product-current-price">{{ currency.unit }}{{ formatPrice(item.min_price) }}</div>
                    <div v-if="item.old_price !== item.min_price" class="product-old-price">{{ currency.unit }}{{ formatPrice(item.old_price) }}</div>
                  </div>
                </template>
              </a-card-meta>
              <div class="product-actions">
                <a-button type="primary" shape="circle" size="middle" @click.stop="addToCart(item)">
                  <template #icon><shopping-cart-outlined /></template>
                </a-button>
                <a-button danger shape="circle" size="middle" @click.stop="removeFromFavorites(item)">
                  <template #icon><delete-outlined /></template>
                </a-button>
              </div>
            </a-card>
          </a-list-item>
        </template>
        <template #footer>
          <div class="pagination-container">
            <div class="total-count">Total <span class="count-highlight">{{ pagination.total }}</span> products</div>
            <a-pagination
              v-if="pagination.total > 0"
              :current="pagination.current"
              :pageSize="pagination.pageSize"
              :total="pagination.total"
              showSizeChanger
              :pageSizeOptions="['12', '24', '48']"
              @change="(page) => handlePageChange(page)"
              @showSizeChange="(current, size) => handleSizeChange(current, size)"
            />
          </div>
        </template>
      </a-list>
    </a-spin>
  </div>

  <a-modal v-model:open="open" width="1200px" title="Product Details" @close="refreshFavorites" :footer="null">
    <ProductDetail.default v-if="open && goodId" :goodId="goodId" @buy="handleBuy" />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useCurrencyStore } from '@/store';
import { ShoppingCartOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { getMyCollect, deleteCollect } from '@/api/user';
import { addCollect } from '@/api/user';
import * as ProductDetail from '@/components/ProductDetail.vue';
import { getFavorites, syncFavoritesFromApi, removeFromFavorites as removeFromFavoritesLocal } from '@/utils/cache';
import {Local,Session} from "@/utils/storage";
import {addFavorite,delFavorite,getFavoriteList} from "@/api/details.ts";
import mitt from 'mitt';
const router = useRouter();
const currencyStore = useCurrencyStore();
const currency = computed(() => currencyStore.currentCurrency);
const { proxy }: any = getCurrentInstance();

// 创建事件发射器实例
const emitter = mitt();
// 货币转换辅助函数（保留作为备用）
const formatPrice = (price: number | string): string => {
  try {
    // 使用全局代理中的货币转换方法
    if (proxy && proxy.$ConvertPrice) {
      return proxy.$ConvertPrice(price, false, false);
    }

    // 备用转换逻辑
    const numPrice = Number(price);
    if (isNaN(numPrice)) return '0';
    const rate = currency.value.rate || 1;
    return (numPrice * rate).toFixed(2);
  } catch (error) {
    console.error('Price conversion error:', error);
    return '0';
  }
};

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timer: number | null = null;
  return function(this: any, ...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 收藏列表数据
const allFavorites = ref([]); // 存储所有收藏数据
const favorites = ref([]); // 当前页显示的收藏数据
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 12,
  total: 0
});

// 获取收藏列表数据
const fetchFavorites = async () => {
  if (loading.value) return; // 如果正在加载中，则不重复请求

  loading.value = true;
  try {
    const res = await getMyCollect({
      page: 1, // 固定请求第一页
      page_size: 300 // 请求较大的数据量，以获取全部数据
    });

    if (res.code === 200) {
      // 保存所有收藏数据
      allFavorites.value = res.result.data || [];
      pagination.value.total = allFavorites.value.length;
      console.log('res.result', res.result)

      // 在前端进行分页处理
      updateDisplayFavorites();

      // 同步到本地缓存
      syncFavoritesFromApi(allFavorites.value);
    } else {
      message.error(res.message || 'Failed to get favorite list');
    }
  } catch (error) {
    console.error('Failed to fetch favorites list:', error);
    message.error('Failed to get favorite list, please try again later');

    // 如果接口请求失败，则使用本地缓存
    allFavorites.value = getFavorites();
    pagination.value.total = allFavorites.value.length;
    updateDisplayFavorites();
  } finally {
    loading.value = false;
  }
};

// 更新当前页显示的收藏数据
const updateDisplayFavorites = () => {
  const startIndex = (pagination.value.current - 1) * pagination.value.pageSize;
  const endIndex = startIndex + pagination.value.pageSize;
  favorites.value = allFavorites.value.slice(startIndex, endIndex);
};

interface Product {
  id: number;
  goods_id: number;
  name: string;
  images: string[];
  min_price: number;
  old_price: number;
  url: string;
}

interface BuyData {
  id: number;
  quantity?: number;
  [key: string]: any;
}

// 查看商品详情
const viewProductDetail = (item: Product) => {
  open.value = true;
  goodId.value = String(item.goods_id);
};

const open = ref<boolean>(false);
const goodId = ref<string | null>(null);
// 添加到购物车
const addToCart = (item: Product) => {
  try {
    open.value = true;
    goodId.value = String(item.goods_id);
    // 检查是否有SKU选项
    // if (item.favorite_sku && item.favorite_sku.length > 0) {
    //   // 如果有多个SKU选项，应导航到商品详情页让用户选择
    //   router.push(`/product/${item.url}`);
    //   message.info('请选择商品规格后加入购物车');
    // } else {
    //   // 如果只有一个SKU或没有SKU，可直接加入购物车
    //   // 这里需要调用添加购物车的API
    //   message.success(`已将 ${item.name} 加入购物车`);
    // }
  } catch (error) {
    console.error('Failed to add to cart:', error);
    message.error('Failed to add to cart, please try again later');
  }
};

// 从收藏中移除
const removeFromFavorites = async (item: Product) => {
  try {
    const res = await deleteCollect({
      goods_id: item.goods_id
    });

    if (res.code === 200) {
      message.success(`${item.name} has been removed from favorites`);

      // 更新本地缓存
      // removeFromFavoritesLocal(item.goods_id);
      favoriteList()

      // 在前端数据中移除该商品
      const itemIndex = allFavorites.value.findIndex(favorite => favorite.goods_id === item.goods_id);
      if (itemIndex !== -1) {
        allFavorites.value.splice(itemIndex, 1);
        // 更新总数
        pagination.value.total = allFavorites.value.length;

        // 如果当前页无数据且不是第一页，则回到上一页
        const maxPage = Math.max(1, Math.ceil(allFavorites.value.length / pagination.value.pageSize));
        if (pagination.value.current > maxPage) {
          pagination.value.current = maxPage;
        }

        // 更新显示的收藏数据
        updateDisplayFavorites();
      }
    } else {
      message.error(res.message || 'Failed to remove from favorites');
    }
  } catch (error) {
    console.error('Failed to remove from favorites:', error);
    message.error('Failed to remove from favorites, please try again later');
  }
};

// 处理购买按钮点击
const handleBuy = (data: BuyData) => {
  // message.success('The product has been successfully added to the cart, please go to the cart for settlement');
  open.value = false;
};

// 分页变化 - 仅页码变化时触发
const handlePageChange = (page: number) => {
  pagination.value.current = page;
  updateDisplayFavorites();
};

// 每页条数变化时触发
const handleSizeChange = (_current: number, size: number) => {
  pagination.value.current = 1; // 切换每页条数时重置到第一页
  pagination.value.pageSize = size;
  updateDisplayFavorites();
};

// 跳转到商品页面
const goToProducts = () => {
  router.push('/products');
};
//收藏列表
const favoriteList = async () => {
  const favoriteRes = await getFavoriteList()
  if(favoriteRes.code === 200){
    emitter.emit('getFavoriteApi');
    Session.set('collectList', favoriteRes.result)
  }
}
// 组件挂载时获取数据
onMounted(() => {
  fetchFavorites();
});

const refreshFavorites = () => {
  fetchFavorites();
};
</script>

<style scoped>
.favorites-container {
  padding: 0;
  background: #fff;
}

/* 列表项样式 */
:deep(.ant-list-item) {
  display: flex;
  padding: 12px;

  .ant-card {
    width: 100%;
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &:hover {
      transform: translateY(-6px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
    }
  }
}

/* 商品图片样式 */
:deep(.ant-card-cover) {
  margin: 0;

  img {
    height: 320px;
    object-fit: cover;
    border-radius: 12px 12px 0 0;
    transition: transform 0.3s ease;
  }
}

/* 商品信息样式 */
:deep(.ant-card-body) {
  padding: 20px;
}

:deep(.ant-card-meta) {
  margin: 0 0 16px;

  .ant-card-meta-title {
    font-size: 15px;
    line-height: 1.4;
    color: #262626;
    margin-bottom: 12px;
    font-weight: 500;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    height: 42px;
    overflow: hidden;
  }
}

/* 价格样式 */
.product-price-container {
  display: flex;
  align-items: baseline;
  gap: 10px;
  margin: 16px 0;
}

.product-current-price {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
  line-height: 1;
}

.product-old-price {
  font-size: 14px;
  color: #8c8c8c;
  text-decoration: line-through;
}

/* 商品操作按钮样式 */
.product-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;

  .ant-btn {
    width: 36px;
    height: 36px;

    &:hover {
      transform: scale(1.05);
      transition: transform 0.2s ease;
    }
  }
}

/* 空状态样式 */
.empty-state {
  padding: 48px 0;
  text-align: center;

  :deep(.ant-empty-description) {
    color: #666;
  }

  .ant-btn {
    margin-top: 16px;
  }
}

/* 分页样式 */
.pagination-container {
  margin-top: 32px;
  padding: 24px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 加载状态样式 */
:deep(.ant-spin) {
  .ant-spin-dot-item {
    background-color: #000;
  }

  .ant-spin-text {
    color: #000;
  }
}

.no-image {
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f0f0;
  color: #999;
}
</style>
